<?php

/**
 * Description of ObjectFunctions
 *
 * @author a.novikov
 */
class ObjectFunctions {
	
	/**
	 *
	 * @param Db_Row|int $source
	 * @param Db_Peer|string $peer
	 * @return Db_Row
	 */
	public static function makeRow(&$source, $peer) {
		self::makePeer($peer);
		if (is_numeric($source)) {
			$source = $peer->fetchById((int)$source);
			if (!$source) {
				throw new Exception('Row does not exist');
			}
		}
		else {
			$rowClassName = $peer->getRowClass();
			if ( !( $source instanceof $rowClassName ) ) {
				throw new InvalidArgumentException('Cannot create row from this source');
			}
		}
		return $source;
	}

	/**
	 *
	 * @param Db_Row|int $source row or id
	 * @return int $id
	 */
	public static function getRowId($source) {
		if (is_numeric($source)) {
			$id = (int)$source;
		}
		elseif ($source instanceof Db_Row) {
			$id = (int)$source->getId();
		}
		else {
			throw new InvalidArgumentException('Invalid source');
		}
		return $id;
	}

	/**
	 *
	 * @param Db_Peer|string $peer
	 * @return Db_Peer
	 */
	public static function makePeer(&$peer) {
		if ( is_string($peer) ) {
			$peer = Factory::getObject($peer);
		}
		
		if ( !($peer instanceof Db_Peer) ) {
			throw new InvalidArgumentException('Cannot create peer from this source');
		}
		return $peer;
	}

	/**
	 *
	 * @param object|string $object
	 * @return string $name object name
	 */
	public static function getClassName($object) {
		if (is_string($object)) {
			if (!class_exists($object)) {
				throw new Exception("Class {$object} does not exist");
			}
			$name = $object;
		}
		elseif (is_object($object)) {
			$name = get_class($object);
		}
		else {
			throw new InvalidArgumentException('Invalid type');
		}
		return $name;
	}
}